package com.zhixiao.user.service.impl

import cn.dev33.satoken.stp.StpUtil
import com.zhixiao.user.mapper.UserMapper
import com.zhixiao.user.model.User
import com.zhixiao.user.model.dto.RegisterDTO
import com.zhixiao.user.service.UserService
import com.zhixiao.user.util.IdGenerator
import org.mindrot.jbcrypt.BCrypt
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

private const val USERNAME_EXISTS_MSG = "用户名已存在"

@Service
class UserServiceImpl : UserService {

    @Autowired
    var userMapper: UserMapper? = null

    @Autowired
    var idGenerator: IdGenerator? = null

    override fun register(registerUser: RegisterDTO): Boolean {
        // 判断用户是否存在
        if (userMapper?.findByUsername(registerUser.username) == 1) {
            throw IllegalArgumentException(USERNAME_EXISTS_MSG)
        }

        // 生成id
        val uuid = idGenerator?.generateId() ?: throw Exception("生成id失败")

        // 生成哈希密码
        val hashedPasswd = BCrypt.hashpw(registerUser.password, BCrypt.gensalt())

        // 初始化用户对象
        val newUser = User(
            uuid = uuid,
            hashedPasswd = hashedPasswd,
            username = registerUser.username,
            nickname = registerUser.nickname ?: registerUser.username,
            age = registerUser.age ?: -1,
            gender = registerUser.gender ?: -1,
            role = registerUser.role ?: 0
        )

        // 保存到数据库
        val result = userMapper?.insert(newUser)
        return result == 1
    }

    override fun login(username: String, password: String): User? {
        // 查询用户信息
        val user = userMapper?.selectByUsername(username) ?: return null

        // 验证密码
        if (BCrypt.checkpw(password, user.hashedPasswd)) {
            // SaToken进行登录
            StpUtil.login(user.uuid)
            // 返回用户信息
            return user
        }
        else {
            return null
        }
    }
}

